package com.abel.bigwater.dataserver.model.h86a

import io.netty.buffer.ByteBuf

class H86APulseChannel(count: Short) : H86AChannelBase<Long>(H86AChannelType.PulseType, count) {
    override fun bufLength() = 1 + 4 + 4 + 2 * (count - 1)

    override fun parseBuffer(buf: ByteBuf): Boolean {
        super.parseBuffer(buf)

        buf.readBytes(bufLength()).apply {
            skipBytes(1)

            yest = readUnsignedInt()

            values.add(readUnsignedInt())

            for (i in 2..count) {
                values.add(values[0] + readUnsignedShort())
            }
        }

        return true
    }

    override fun pack(buf: ByteBuf): Boolean {
        buf.alloc().buffer().apply {
            super.pack(this)

            writeInt(yest!!.toInt())

            writeInt(values[0].toInt())

            for (i in 2..count) {
                writeShort((values[i - 1] - values[0]).toInt())
            }

            buf.writeBytes(this)
        }

        return true
    }
}